layui.use(['upload', 'layer'],function () {
    var form = layui.form
        ,upload = layui.upload
        ,layer = layui.layer;

    //文件上传
    upload.render({
        elem: '#file-upload'
        ,url: '/user/upload/temp/file.json'
        ,accept: 'file'
        ,done: function(json){
            if(json.code === 0){
                layer.msg(json.msg, {icon: 1});
                $("#fileSize").val(json.data.size)
                $("#fileUrl").val(json.data.src)
                $("#title").val(json.data.title)
            }else {
                layer.msg(json.msg, {icon: 2});
            }

        }
    });

    //图片封面上传
    var uploadInst = upload.render({
        elem: '#cover-upload'
        ,url: '/user/upload/cover.json'
        ,done: function(json){
            if(json.code === 0){
                layer.msg(json.msg, {icon: 1});
                $('#cover').val(json.data.src);
            }else {
                layer.msg(json.msg, {icon: 2});
            }
        }
    });

    //封面预览
    $('#view-cover').click(function () {
        var imgSrc = $('#cover').val();
        if (imgSrc.length < 1) {
            layer.msg('图片地址不存在！');
        } else {
            layer.open({
                type: 1,
                skin: 'layui-layer-rim',
                title: false,
                area: ['480', '365px'],
                content: '<img src="' + imgSrc + '" />'
            });
        }
    });

})

function addDocument() {
    var categoryId = $('#categoryId').val();
    if (categoryId === '' || categoryId === '0') {
        return layer.msg('请先选择所属分类！', {icon: 2});
    }
    if ($('#title').val().length < 3) {
        return layer.msg('请输入标题，且必需大于3个字符！', {icon: 2});
    }
    var index = layer.load(0, {shade: false});
    var data = $("#form-document-add").serializeArray();
    $.post("/user/document/add.json", data, function (result) {
        if (result.code === 0) {
            layer.close(index)
            layer.msg(result.msg, {icon: 1});
            setTimeout(function () {
                location.reload()
            },1200)
        } else {
            layer.close(index)
            layer.msg(result.msg, {icon: 2});
        }
    });
}

function editDocument() {
    var categoryId = $('#categoryId').val();
    if (categoryId === '' || categoryId === '0') {
        return layer.msg('请先选择所属分类！', {icon: 2});
    }
    if ($('#title').val().length < 3) {
        return layer.msg('请输入标题，且必需大于3个字符！', {icon: 2});
    }
    var index = layer.load(0, {shade: false});
    var data = $("#form-document-edit").serializeArray();
    $.post("/user/document/edit.json", data, function (result) {
        if (result.code === 0) {
            layer.close(index)
            layer.msg(result.msg, {icon: 1});
            setTimeout(function () {
                location.reload()
            },1200)
        } else {
            layer.close(index)
            layer.msg(result.msg, {icon: 2});
        }
    });
}